//
//  BMTipsView.m
//  ZJNews
//
//  Created by Tang Haibo on 11-11-11.
//  Modify by meng lv on 12-6-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BMTipsView.h"
#define kTipsViewInterval 5.0f
#define kTipsBorderMargin 30.0f
#define kTipsFont [UIFont systemFontOfSize:15.0f]
#define kTipsLabelLeftMargin 10.0f
#define kTipsLabelTopMargin 5.0f

#define kBMTipsViewBackDayColor COLOR_RGBA(0, 0, 0, 0.8)
#define kBMTipsViewBackNightColor COLOR_RGBA(255, 255, 255, 0.8)

#define kBMTipsViewTextDayColor [UIColor whiteColor]
#define kBMTipsViewTextNightColor [UIColor blackColor]

@interface BMTipsView()
{
    UIColor     *_textColor;
    UIColor     *_backColor;
}

@property (nonatomic, retain) NSTimer *timer;

- (void)moveTipsview:(BMTipsView *)tipsview to:(PopDir)toDir;
- (void)startTimer;
- (void)stopTimer;
@end

@implementation BMTipsView
@synthesize tips = _tips;
@synthesize timer = _timer;
@synthesize isNightStyle = _isNightStyle;
@synthesize inview = _inview;

#pragma mark - lifecycle
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    RELEASE_SAFELY(_tips);
    [_timer invalidate];
    self.timer = nil;
    RELEASE_SAFELY(_titleLabel);
    RELEASE_SAFELY(_inview);
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        _isNightStyle = NO;
        self.layer.cornerRadius = 2.0f;
        _titleLabel = [[UILabel alloc] initWithFrame:
                       CGRectMake(kTipsLabelLeftMargin, 
                                  kTipsLabelTopMargin, 
                                  self.bounds.size.width - 2 * kTipsLabelLeftMargin,
                                  self.bounds.size.height - 2 * kTipsLabelTopMargin)];
        _titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.numberOfLines = 0;
        _titleLabel.textAlignment = UITextAlignmentCenter;
        _titleLabel.textColor = _textColor;
        self.backgroundColor = _backColor;
//        if (_isNightStyle)
//        {
//            self.backgroundColor = kBMTipsViewBackNightColor;
//            _titleLabel.textColor = kBMTipsViewTextNightColor;
//        }
//        else
//        {
//            _titleLabel.textColor = kBMTipsViewTextDayColor;
//            self.backgroundColor = kBMTipsViewBackDayColor;
//        }
        _titleLabel.font = kTipsFont;
        [self addSubview:_titleLabel];
    }
    return self;
}

- (void)setIsNightStyle:(BOOL)isNightStyle
{
    if (_isNightStyle != isNightStyle)
    {
        _isNightStyle = isNightStyle;
        if (_isNightStyle)
        {
            self.backgroundColor = kBMTipsViewBackNightColor;
            _titleLabel.textColor = kBMTipsViewTextNightColor;
        }
        else
        {
            self.backgroundColor = kBMTipsViewBackDayColor;
            _titleLabel.textColor = kBMTipsViewTextDayColor;
        }
    }
}

- (void)deviceOrientationDidChange:(NSNotification *)notification
{
    //从上往下显示
    if (PopDirBottom == _toDir)
    {
        self.frame = CGRectMake(floor((self.superview.bounds.size.width - _size.width)/2), 
                            kTipsBorderMargin,
                            _size.width, 
                            _size.height);
    }
    
    //从下往上显示
    if (PopDirTop == _toDir)
    {
        self.frame = CGRectMake(floor((self.superview.bounds.size.width - _size.width)/2), 
                            self.superview.bounds.size.height - _size.height - kTipsBorderMargin,
                            _size.width, 
                            _size.height);
    }
}

- (id)initWithTips:(NSString *)tips 
           andSize:(CGSize)size
             toDir:(PopDir)toDir
            inView:(UIView*)view 
       autoDismiss:(BOOL)autoDismiss 
             inSec:(NSInteger)sec
         textColor:(UIColor *)textColor
         backColor:(UIColor *)backColor
{
    if (textColor != nil)
    {
        _textColor = textColor;
    }
    else
    {
        _textColor = kBMTipsViewTextDayColor;
    }
    if (backColor != nil)
    {
        _backColor = backColor;
    }
    else
    {
        _backColor = kBMTipsViewBackDayColor;
    }
    CGSize wordSize = [tips sizeWithFont:kTipsFont 
                       constrainedToSize:CGSizeMake(size.width - 2 * kTipsLabelLeftMargin, 1500)];
    CGRect rect = CGRectMake(floor((view.bounds.size.width - size.width)/2),
                             0,
                             size.width, 
                             (size.height>(wordSize.height + 2 * kTipsLabelTopMargin))?size.height:(wordSize.height + 2 * kTipsLabelTopMargin));
    self = [self initWithFrame:rect];
    if (self) 
    {
        self.tips = tips;
        _toDir = toDir;
        self.inview = view;
        _autoDismiss = autoDismiss;
        _dismisSec = sec;
        _size = self.frame.size;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) 
                                                 name:UIDeviceOrientationDidChangeNotification object:nil];
    
    self.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
    
    return self;
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */
#pragma mark - public function
- (void)dismiss
{
    [self.timer invalidate];
    self.timer = nil;
    CGRect toRect = CGRectZero;
    //从上往下显示
    CGRect tmpRect = self.frame;
    NSInteger tipsNum = 0;
    for (UIView *view in self.inview.subviews)
    {
        if ([view isKindOfClass:[BMTipsView class]])
        {
            tipsNum++;
            if (tipsNum > 1)
            {
                break;
            }
        }
    }

    if (PopDirBottom == _toDir) 
    {
        toRect = CGRectMake(tmpRect.origin.x, 
                            -_size.height,
                            tmpRect.size.width, 
                            _size.height);
    }
    
    //从下往上显示
    if (PopDirTop == _toDir) 
    {
        toRect = CGRectMake(tmpRect.origin.x, 
                            self.inview.bounds.size.height,
                            tmpRect.size.width, 
                            _size.height);
    }
    
    [UIView animateWithDuration:0.5 
                          delay:0 
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         if (tipsNum > 1)
                         {
                             self.alpha = 0;
                         }
                         else
                         {
                             self.frame = toRect;
                         }
                     }
                     completion:^(BOOL finished) 
                     {
                         [self retain];
                         if (self.superview!=nil) 
                         {
                             [self removeFromSuperview];
                         }
                         
                         //遍历superview将上层/下层 BMTipsView 下移/上移
                         [self.inview.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                             if ([obj isKindOfClass:[BMTipsView class]]) {
                                 BMTipsView *tipsview = obj;
                                 if (tipsview.frame.origin.y<self.frame.origin.y) {
                                     //下移self height
                                     PopDir todir = PopDirTop;
                                     if (PopDirTop==_toDir) 
                                     {
                                         todir = PopDirBottom;
                                     }
                                     [self moveTipsview:tipsview to:todir];
                                 }
                             }
                         }];
                         self.inview = nil;
                         [self release];
                     }];
}

- (void)showTips:(NSString *)tips 
           toDir:(PopDir)toDir 
            size:(CGSize)size
          inView:(UIView*)view 
     autoDismiss:(BOOL)autoDismiss 
           inSec:(NSInteger)sec
{
    if (view == nil || tips== nil || [tips length] == 0)
    {
        return;
    }
    
    //reset member data
    self.tips = tips;
    _toDir = toDir;
    self.inview = view;
    _autoDismiss = autoDismiss;
    _dismisSec = sec;
    _size = size;
    
//    CGFloat originAlpha = 0.2;
//    CGFloat toAlpha = 1.f;
    CGRect originRect = CGRectZero;
    CGRect toRect = CGRectZero;
    
    //遍历view上面的tipsview,全部移动一个高度的位移
    [view.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) 
    {
        if ([obj isKindOfClass:[self class] ]) {
            BMTipsView *tipsview = obj;
            [self moveTipsview:tipsview to:toDir];
        }
    }];
    
    //从上往下显示
    if (PopDirBottom == toDir)
    {
        originRect = CGRectMake(floor((view.bounds.size.width - size.width)/2), 
                                -size.height,
                                size.width, 
                                size.height);
        toRect = CGRectMake(floor((view.bounds.size.width - size.width)/2), 
                            kTipsBorderMargin,
                            size.width, 
                            size.height);
    }
    
    //从下往上显示
    if (PopDirTop == toDir)
    {
        originRect = CGRectMake(floor((view.bounds.size.width - size.width)/2), 
                                view.bounds.size.height,
                                size.width, 
                                size.height);
        toRect = CGRectMake(floor((view.bounds.size.width - size.width)/2), 
                            view.bounds.size.height - size.height - kTipsBorderMargin,
                            size.width, 
                            size.height);
    }
    
    //动画
    self.frame = originRect;
//    self.alpha = originAlpha;
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut 
                     animations:^{
                         self.frame = toRect;
//                         self.alpha = toAlpha;
                     }
                     completion:^(BOOL finished) {
                         //do nothing
                     }];
    
    _titleLabel.text = tips;
    [view addSubview:self];
    
    if (autoDismiss) 
    {
        //打开定时器，sec秒后自动关闭
        [self startTimer];
        
    }
}

- (void)showTips{
    [self showTips:self.tips 
             toDir:_toDir  
              size:self.bounds.size
            inView:self.inview
       autoDismiss:_autoDismiss 
             inSec:_dismisSec];
}

#pragma mark - private function
- (void)moveTipsview:(BMTipsView *)tipsview to:(PopDir)toDir
{
    CGRect toRect = CGRectZero;
    //从上往下显示
    CGRect tmpRect = tipsview.frame;
    if (PopDirBottom == toDir) 
    {
        toRect = CGRectMake(tmpRect.origin.x, 
                            tmpRect.origin.y+_size.height + kTipsViewInterval,
                            tmpRect.size.width, 
                            tmpRect.size.height);
    }
    
    //从下往上显示
    if (PopDirTop == toDir)
    {
        toRect = CGRectMake(tmpRect.origin.x, 
                            tmpRect.origin.y - _size.height - kTipsLabelTopMargin,
                            tmpRect.size.width, 
                            tmpRect.size.height);
    }
    
    //动画
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut 
                     animations:^{
                         tipsview.frame = toRect;
                     }
                     completion:^(BOOL finished) {
                         //do nothing
                     }];
}

#pragma mark timer
- (void)timerFire:(id)sender{
    if (self.superview!=nil) {
        [self dismiss];
    }
}

- (void)startTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:_dismisSec
                                                  target:self
                                                selector:@selector(timerFire:) 
                                                userInfo:nil 
                                                 repeats:NO];
}

- (void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

@end

